﻿package com.powerunion.extjs.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Download extends HttpServlet {

    private String downloadPath = "C:\\download\\"; // 用于存放下载文件的目录
    public void init() throws ServletException {
    	downloadPath = this.getInitParameter("downloadPath");
    }
    
    protected   void   doGet(HttpServletRequest   request,   HttpServletResponse   response)   
    throws   ServletException,   IOException   {   
    	this.doPost(request, response);
    }   
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
{		
        String filepara = request.getParameter("filename");
        String aFileName = this.getInitParameter(filepara);
        FileInputStream in = null; // 输入流
        ServletOutputStream out = null; // 输出流

        try {
         response.reset();
         response.setHeader("Content-Disposition",   "attachment;filename="+aFileName);   
                  response.setHeader("Connection","close");   
                  response.setHeader("Content-Type","application/octet-stream"); 
      //   response.setContentType("text/plain");
      //   response.setHeader("Content-disposition", "attachment; filename="
//           + aFileName);
                  
         in = new FileInputStream(downloadPath + aFileName); // 读入文件
         out = response.getOutputStream();
         out.flush();
         int aRead = 0;
         while ((aRead = in.read()) != -1 & in != null) {
          out.write(aRead);
         }
         out.flush();
        } catch (Throwable e) {
         //log.error("FileDownload doGet() IO error!", e);
        } finally {
	         try {
	          in.close();
	          out.close();
	         } catch (Throwable e) {
	          //log.error("FileDownload doGet() IO close error!", e);
	         }
        }
}


}

